#include "ftputil.h"
#include <QMessageBox>
#include "sysconf.h"

extern QByteArray pstxt;
extern RunState runState;
extern QByteArray rcstxt;
extern QByteArray profiletxt;


FtpUtil::FtpUtil()
{
    retryCount=0;
}

void FtpUtil::initConn(const QString &ip, const QString &username, const QString &password)
{
    this->ftpip=ip;
    this->username=username;
    this->password=password;
}


bool FtpUtil::connectFtp()
{
    if(ftp!=0)
    {
        return true;
    }
    ftp=new QFtp;
    connect(ftp, SIGNAL(commandFinished(int,bool)),this, SLOT(ftpCommandFinished(int,bool)));
    connect(ftp, SIGNAL(commandStarted(int)),this, SLOT(ftpCommandStarted(int)));
    connect(ftp,SIGNAL(rawCommandReply(int,QString)),this,SLOT(ftpRawCommandReply(int,QString)));
    connect(ftp, SIGNAL(listInfo(QUrlInfo)),this, SLOT(addToList(QUrlInfo)));

    ftp->connectToHost(ftpip);
    ftp->login(username,password);

    return true;
}

bool FtpUtil::closeFtp()
{
    if (ftp)

    {
        qDebug("close ftp");
        ftp->abort();
        ftp->deleteLater();
        ftp = 0;
    }
    return true;
}

bool FtpUtil::upload(const FileBean &bean)
{

    QFile *file=new QFile(bean.filename);
    if(!file->open(QIODevice::ReadOnly))
    {
        //QMessageBox::critical(this,"提示",QString("打开:%1失败").arg(bean.filename));
        return false;
    }
    //qDebug("%s",qPrintable(bean.remotePath));
    if(runState.integratedpower&&bean.remotePath=="/home/integrate/integratedpower")
    {
        QString msg;
        msg=QString("/home/integrated/integratedpower:正在运行,上传失败");
        emit updateStatus(FTP,WARN,msg);
        return false;
    }
    if(runState.watchdog&& bean.remotePath=="/home/util/watchdog")
    {
        QString msg;
        msg=QString("/home/util/watchdog:正在运行,上传失败");
        emit updateStatus(FTP,WARN,msg);
        return false;
    }
    if(runState.scl_srvr_n&&bean.remotePath=="/home/mmslite/scl_srvr_n")
    {
        QString msg;
        msg=QString("/home/mmslite/scl_srvr_n:正在运行,上传失败");
        emit updateStatus(FTP,WARN,msg);
        return false;
    }

    int cmdid=ftp->put(file,bean.remotePath.toLatin1());
    logInfo[cmdid]=bean.remotePath;
    return true;
}

 bool FtpUtil::upload(const QList<FileBean> &beanlist)
 {
     for(int i=0;i<beanlist.size();i++)
     {
         this->upload(beanlist.at(i));
     }
     return true;
 }

 void FtpUtil::upload(const QByteArray & data, const QString & file)
 {
     ftp->put(data,file);
 }

 bool FtpUtil::isconnect()
 {
     if(ftp->state()==QFtp::Unconnected||ftp->state()==QFtp::HostLookup||ftp->state()==QFtp::Connecting||ftp->state()==QFtp::Closing)
     {
         return false;
     }
     return true;

 }

 void FtpUtil::download(const QString &filename)
 {
     int cmdid=ftp->get(filename);
     logInfo[cmdid]=filename;
 }

 bool FtpUtil::mkdir(const QString &dir)
 {

    int cmdid=ftp->mkdir(dir);
    logInfo[cmdid]=dir;
    return true;
 }

 bool FtpUtil::mkdir(const QStringList &dirlist)
 {
     for(int i=0;i<dirlist.size();i++)
     {
         this->mkdir(dirlist.at(i));
     }
     return true;
 }

 bool FtpUtil::rmdir(const QString &dir)
 {
     int cmdid=ftp->rmdir(dir);
     logInfo[cmdid]=dir;
     return true;
 }

 bool FtpUtil::rm(const QString &filename)
 {
     int cmdid=ftp->remove(filename);
     logInfo[cmdid]=filename;
     return true;
 }

 bool FtpUtil::rm(const QStringList &filelist)
 {
     for(int i=0;i<filelist.size();i++)
     {
         this->rm(filelist.at(i));
     }
     return true;
 }

 void FtpUtil::cd(const QString &dir)
 {
     int cmdid=ftp->cd(dir);
     logInfo[cmdid]=dir;
 }


 void FtpUtil::ftpCommandFinished(int commandId, bool error)
 {
     if (ftp->currentCommand() == QFtp::ConnectToHost)
     {
         if (error)
         {
             QString msg;
             msg=QString("不能连接到FTP服务器:%1").arg(ftpip);
             emit updateStatus(FTP,ERROR,msg);
             closeFtp();
             return;
         }
         else
         {
             QString msg;
             msg=QString("成功连接到FTP服务器:%1").arg(ftpip);
             emit updateStatus(FTP,NORMAL,msg);
             return;
         }
     }
     if (ftp->currentCommand() == QFtp::Login)
     {
         if(error)
         {
             QString msg;
             msg=QString("登录到FTP服务器失败:%1,可能是用户名或密码错误").arg(ftpip);
             emit updateStatus(FTP,ERROR,msg);
             closeFtp();
             return;
         }
         else
         {
             QString msg;
             msg=QString("登录到FTP服务器成功:%1").arg(ftpip);
             emit updateStatus(FTP,NORMAL,msg);
             getBoxInfo();
             return;
         }
     }
     if (ftp->currentCommand() == QFtp::Put)
     {
         if (error)
         {
             QString msg;
             msg=QString("%1上传失败,信息:%2").arg(logInfo[commandId]).arg(ftp->errorString());
             emit updateStatus(FTP,ERROR,msg);
         }
         else
         {
             QString msg;
             msg=QString("%1上传成功").arg(logInfo[commandId]);
             emit updateStatus(FTP,NORMAL,msg);
         }
     }
     if (ftp->currentCommand() == QFtp::Get)
     {
         if (error)
         {
//             QString msg;
//             msg=QString("%1上传失败,信息:%2").arg(logInfo[commandId]).arg(ftp->errorString());
//             emit updateStatus(FTP,ERROR,msg);
         }
         else
         {
             if(logInfo[commandId]=="/home/util/ps.txt")
             {
                 pstxt=ftp->readAll();
                 emit updateRunstate();
             }
             if(logInfo[commandId]=="/etc/init.d/rcS")
             {
                 rcstxt=ftp->readAll();
                // qDebug("%s",qPrintable(QString(profiletxt)));
             }
             if(logInfo[commandId]=="/etc/profile")
             {
                 profiletxt=ftp->readAll();
                 //qDebug("%s",qPrintable(QString(profiletxt)));
                 emit setBoxInfo();
             }
//             emit updateStatus(FTP,NORMAL,msg);
         }
     }
     if(ftp->currentCommand()==QFtp::Cd)
     {
         if(error)
         {
             QString msg;
             msg=QString("CD:%1目录时发生错误,信息:%2").arg(logInfo[commandId]).arg(ftp->errorString());
             emit updateStatus(FTP,ERROR,msg);
         }
         else
         {

         }
     }
     if (ftp->currentCommand() == QFtp::Mkdir)
     {
         if (error)
         {
             QString msg;
             msg=QString("创建:%1目录时发生错误,信息:%2").arg(logInfo[commandId]).arg(ftp->errorString());
             emit updateStatus(FTP,ERROR,msg);
             //ftp->clearPendingCommands();
         }
         else
         {
             QString msg;
             msg=QString("创建:%1目录成功").arg(logInfo[commandId]);
             emit updateStatus(FTP,NORMAL,msg);
         }
     }
 }


 void FtpUtil::ftpCommandStarted(int)
 {
     if(ftp->currentCommand() == QFtp::ConnectToHost)
     {
         emit updateStatus(FTP,NORMAL,"正在连接到服务器…");
     }
     if (ftp->currentCommand() == QFtp::Login)
     {
         emit updateStatus(FTP,NORMAL,"正在登录…");
     }

     if (ftp->currentCommand() == QFtp::Put)
     {
        //emit updateStatus(FTP,NORMAL,"正在上传文件…");
     }
     else if (ftp->currentCommand() == QFtp::Close)
     {
         emit updateStatus(FTP,NORMAL,"正在关闭…");
     }

 }

 void FtpUtil::ftpRawCommandReply( int replyCode, const QString & detail )
 {
     QString msg;
     msg=QString("响应码:%1,信息:%2").arg(replyCode).arg(detail);
     emit updateStatus(FTP,NORMAL,msg);
 }

 void FtpUtil::addToList(const QUrlInfo &info)
 {
     emit addToRemote(info);
 }

 void FtpUtil::list()
 {
     emit clearRemoteView();
     ftp->list();
 }

 void FtpUtil::getBoxInfo()
 {
     this->download("/etc/init.d/rcS");
     this->download("/etc/profile");
 }


